<?php

namespace Encore\Admin\Config;

use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Model;

class ConfigModel extends Model
{
    /**
     * Settings constructor.
     *
     * @param array $attributes
     */
    public function __construct($attributes = [])
    {
        parent::__construct($attributes);

        $this->setConnection(config('admin.database.connection') ?: config('database.default'));

        $this->setTable(config('admin.extensions.config.table', 'admin_config'));
    }


    protected $casts = [
        'value' => 'json',
    ];

    public function setConfig($dotKey,$value)
    {
        
        $keys = explode(".", $dotKey);
        $rootKey = $keys[0];
        $config = config($rootKey);
        if(!$config){
            return 'dotkey is not exist.';
        }
        if(count($keys)>1){
            unset($keys[0]);
            $arrKey = implode('.',$keys);
            Arr::set($config, $arrKey, $value);
        }else{
            $config = $value;
        }
        $this->where('name',$rootKey)->update(['value'=>$config]);
        return 'success';
    }

}
